# coding=UTF-8
#This file is part of Nereid.  The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import logging

from proteus import config, Model 
from werkzeug import Request, ClosingIterator, run_simple
from werkzeug import redirect as redirect
from werkzeug.exceptions import HTTPException

from utilities import   local, \
                        local_manager, \
                        generate_url_map, \
                        CallableProxyHandler

class Service(object):
    """
    Main Object to create an instance of for the wsgi service
    or simple server in the case of debugging
    """
    def __init__(self,
                 database_name,
                 user='admin',
                 database_type='postgresql',
                 language='en_US',
                 password='',
                 ):
        """
        @param database_name:   Name of the Tryton database nereid has to
                                connect to.
        @param user: Username of the res.user in Tryton
        @param database_type: Argument for proteus on the database type
        @param language: ISO code of default language
        @param password: Password of the user whent he connection is via RPC
        """
        self.database_name = database_name
        self.user = user
        self.database_type = database_type
        self.language = language
        self.password = password
        self._connect()
        super(Service, self).__init__()
    
    def _connect(self):
        """
        Initialises connection to server via Proteus
        Logs INFO in the server side about the login
        """
        try:
            config.set_trytond(
                               self.database_name,
                               self.user,
                               self.database_type,
                               self.language,
                               self.password)
            User = Model.get('res.user')
            currentuser = User.find([('login', '=', self.user)])[0]
            logging.info(
                "Connection established to Tryton for " + currentuser.name)
        except Exception, e:
            raise e
        return True
        
    def __call__(self, environ, start_response):
        """
        The WSGI application should be a callable
        
        @param environ: The WSGI environment contains all the information 
        the user request transmit to the application. It is passed to the 
        WSGI application by Werkzeug
        
        @param start_response: Used to send data back to the client.So what 
        you are doing according to werkzeug is not returning the response 
        objects from your WSGI application but calling it as WSGI application 
        inside your WSGI application and returning the return value of that call. 
        """
        local.application = self
        request = Request(environ)
        url_map = generate_url_map()
        local.url_adapter = adapter = url_map[
                                  environ.get('HTTP_HOST')
                                            ].bind_to_environ(environ)
        try:
            endpoint, values = adapter.match()
            handler = CallableProxyHandler(endpoint)
            response = handler(request, values)
        except HTTPException, e:
            return e(environ, start_response)
        return response(environ, start_response)


def run_simple_server(
                hostname='localhost',
                port=8000,
                application=None,
                use_reloader=False, use_debugger=True,
                *args, **kwargs):
    """
    Warning: development server is not intended to be used on 
                production systems.
    
    The following documentation is a copy of the documentation from
    werkzeug documentation
    
    Refer: http://werkzeug.pocoo.org/documentation/dev/serving.html
    
    hostname     – The host for the application. eg: 'localhost'
    port         – The port for the server. eg: 8080
    application  – the WSGI application to execute
    use_reloader – should the server automatically restart the 
                    python process if modules were changed?
    use_debugger – should the werkzeug debugging system be used?
    use_evalex   – should the exception evaluation feature be enabled?
    extra_files  – a list of files the reloader should watch additionally 
                    to the modules. For example configuration files.
    reloader_interval – the interval for the reloader in seconds.
    threaded     – should the process handle each request in a separate 
                 thread?
    processes    – number of processes to spawn.
    request_handler – optional parameter that can be used to replace the 
                    default one. You can use this to replace it with a 
                    different BaseHTTPRequestHandler subclass.
    static_files – a dict of paths for static files. This works exactly like 
                    SharedDataMiddleware, it’s actually just wrapping the 
                    application in that middleware before serving.
    passthrough_errors – set this to True to disable the error catching. 
                    This means that the server will die on errors but it 
                    can be useful to hook debuggers in (pdb etc.)
    ssl_context  – an SSL context for the connection. 
                    Either an OpenSSL context, the string 'adhoc' if the 
                    server should automatically create one, or None to 
                    disable SSL (which is the default).
    """
    run_simple(hostname, port, application,
                 use_reloader, use_debugger,
                 *args, **kwargs)
